# coding = utf-8
import os
import logging
import time
from wsgiref.util import FileWrapper

from django.http import HttpResponse
from django.utils.encoding import escape_uri_path
from document.api.serializers import LoanNoteSerializer
from document.models import LoanNote
from lawoffice import settings
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

import pandas as pd
import numpy as np
from docxtpl import DocxTemplate
import zipfile
import tempfile
import shutil
import locale

logger = logging.getLogger("django")


class LoanNoteViewSet(ModelViewSet):
    # authentication_classes = ()
    permission_classes = ()
    queryset = LoanNote.objects.all()
    serializer_class = LoanNoteSerializer

    def get_queryset(self):
        queryset = super().get_queryset()
        user = self.request.user

        search_date = self.request.query_params.getlist("search_date[]")

        if user:
            queryset = queryset.filter(user=user)

        if search_date and len(search_date) == 2:
            queryset = queryset.filter(add_time__range=(search_date[0], search_date[1]))

        return queryset

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)

    @action(methods=['POST'], detail=False)
    def create_note(self, request, *args, **kwargs):
        user = self.request.user

        search_date = self.request.data.get("search_date")

        queryset = self.serializer_class.Meta.model.objects.all()

        if user:
            queryset = queryset.filter(user=user)
        else:
            queryset = self.serializer_class.Meta.model.objects.none()

        if search_date and len(search_date) == 2:
            queryset = queryset.filter(add_time__range=(search_date[0], search_date[1]))
        # window使用
        # locale.setlocale(locale.LC_ALL, 'en')
        # locale.setlocale(locale.LC_CTYPE, 'chinese')
        if queryset:
            df = pd.DataFrame(list(queryset.values()))

            df["loan_begin_date"] = pd.to_datetime(df["loan_begin_date"], format="%Y-%m-%d")
            df["loan_end_date"] = pd.to_datetime(df["loan_end_date"], format="%Y-%m-%d")
            df["interest_settle_time"] = pd.to_datetime(df["interest_settle_time"], format="%Y-%m-%d")
            df['loan_begin_date'] = df['loan_begin_date'].dt.strftime("%Y年%m月%d日")
            df['loan_end_date'] = df['loan_end_date'].dt.strftime("%Y年%m月%d日")
            df['interest_settle_time'] = df['interest_settle_time'].dt.strftime("%Y年%m月%d日")

            df.rename(columns={
                "cate": "身份属性",
                "lender_name": "出借人姓名",
                "lender_ident": "出借人身份证",
                "borrower_name": "借款人姓名",
                "borrower_ident": "借款人身份证",
                "co_borrower_name": "共同借款人姓名",
                "co_borrower_ident": "共同出借人身份证",
                "borrower_address": "借款人家庭地址",
                "borrower_phone": "借款人手机",
                "borrower_wechat": "借款人微信",
                "borrower_unit_address": "借款人单位地址",
                "borrower_unit_phone": "借款人单位电话",
                "guarantor_name": "保证人姓名",
                "guarantor_ident": "保证人身份证",
                "guarantor_address": "保证人家庭地址",
                "guarantor_phone": "保证人手机",
                "guarantor_wechat": "保证人微信",
                "guarantor_unit_address": "保证人单位地址",
                "guarantor_unit_phone": "保证人单位电话",
                "loan_usage": "借款用途",
                "loan_money": "借款金额小写",
                "loan_word_money": "借款金额大写",
                "loan_term": "借款期限",
                "loan_begin_date": "开始日期",
                "loan_end_date": "截止日期",
                "repay_account_name": "还款账户名称",
                "repay_account": "还款账户",
                "repay_bank": "还款开户银行",
                "interest_unit_time": "计息单位时间",
                "interest": "利息",
                "interest_settle_time": "利息结算时间",
                "date_penalty": "日违约金",
                "collateral": "抵押物",
                "user": "录入人",
                "update_time": "修改时间",
                "add_time": "增加时间",
            }, inplace=True)

            df = df.replace(np.nan, '')  # 空值时不显示nan，显示为空格
            dirpath = settings.MEDIA_ROOT + '/document/template/loan'
            startdir = dirpath + '/借条'  # 要压缩的文件夹路径
            if not os.path.exists(startdir):
                os.makedirs(startdir)

            for index, row in df.iterrows():
                dict_row = dict(row)
                if dict_row["身份属性"] == 0:
                    doc = DocxTemplate(dirpath + '/借条模板-出借人.docx')  # 加载模板文件
                elif dict_row["身份属性"] == 1:
                    doc = DocxTemplate(dirpath + '/借条模板-借款人.docx')  # 加载模板文件
                else:
                    doc = DocxTemplate(dirpath + '/借条模板-保证人.docx')  # 加载模板文件

                doc.render(dict_row)  # 填充数据
                if dict_row["身份属性"] == 0:
                    doc.save(dirpath + '/借条/{}-{}.docx'.format(dict_row['出借人姓名'], dict_row['出借人身份证']))  # 保存目标文件
                elif dict_row["身份属性"] == 1:
                    doc.save(dirpath + '/借条/{}-{}.docx'.format(dict_row['借款人姓名'], dict_row['借款人身份证']))  # 保存目标文件
                else:
                    doc.save(dirpath + '/借条/{}-{}.docx'.format(dict_row['保证人姓名'], dict_row['保证人身份证']))  # 保存目标文件

            temp = tempfile.TemporaryFile()
            z = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
            for dirpath, dirnames, filenames in os.walk(startdir):
                fpath = dirpath.replace(startdir, '')
                fpath = fpath and fpath + os.sep or ''
                for filename in filenames:
                    z.write(os.path.join(dirpath, filename), fpath + filename)
            z.close()
            file_lens = temp.tell()
            temp.seek(0)
            wrapper = FileWrapper(temp)
            shutil.rmtree(startdir)
            response = HttpResponse(wrapper, content_type='application/octet-stream')
            file_name = '借条_{}.zip'.format(time.strftime('%Y%m%d'))
            response['Content-Disposition'] = 'attachment; filename={}'.format(escape_uri_path(file_name.encode('utf-8')))
            response['Content-Length'] = file_lens
            return response

        # return Response(data={}, status=status.HTTP_204_NO_CONTENT)
